package gconfig

import (
	"encoding/json"
	"io/ioutil"
	"path/filepath"
	"strings"
	"sync"
)

type Config struct {
	file string
	data map[string]interface{}
}

var config *Config
var once sync.Once
var Instance = getInstance()

func getInstance() *Config {
	once.Do(func() {
		config = &Config{}
	})

	return config
}

func (c *Config) load() {
	if !filepath.IsAbs(c.file) {
		file, err := filepath.Abs(c.file)
		if err != nil {
			panic(err)
		}
		c.file = file
	}

	data, err := ioutil.ReadFile(c.file)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(data, &c.data)
	if err != nil {
		panic(err)
	}
}

func (c *Config) InitConfig(path string) {
	c.file = path
	c.data = make(map[string]interface{})
	c.load()
}

func (c *Config) Get(key string) interface{} {
	keys := strings.Split(key, " -> ")
	l := len(keys)
	if l == 1 {
		return c.data[key]
	}

	var value interface{}
	for i := 0; i < l; i++ {
		if i == 0 {
			value = c.data[keys[i]]
			if value == nil {
				return nil
			}
		} else {
			if v, ok := value.(map[string]interface{}); ok {
				value = v[keys[i]]
			} else {
				if l == i-1 {
					return value
				}
				return nil
			}
		}
	}
	return value
}
